﻿using System;
using System.IO;
using System.IO.Compression;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Threading;
using Launcher;
using LiteDB;
using PackagingTool.ViewModels;

namespace PackagingTool.Views;

public partial class BuildPlan : Window
{
    public BuildPlan()
    {
        InitializeComponent();

        DataContextChanged += OnDataContextChanged;
    }

    private BuildPlanViewModel ViewModel => (BuildPlanViewModel)DataContext;

    private async void OnDataContextChanged(object? sender, EventArgs e)
    {
        await StartBuild();
    }

    private async Task StartBuild()
    {
        using var database = new LiteDatabase(ViewModel.Path);

        int size = 0;


        var assembly = database.GetCollection<MainAssembly>();

        foreach (var fileItem in ViewModel.SelectFileItems)
        {
            await using var fileStream = new FileStream(fileItem.Path, FileMode.Open, FileAccess.Read);
            using var compressedStream = new MemoryStream();
            await using var gzipStream = new GZipStream(compressedStream, CompressionMode.Compress, true);

            await fileStream.CopyToAsync(gzipStream);
            gzipStream.Close(); // Make sure to close the compression stream

            compressedStream.Position = 0; // Reset the position for reading

            database.FileStorage.Upload(fileItem.Path, fileItem.Name, compressedStream);
            size++;

            await Dispatcher.UIThread.InvokeAsync(() =>
                ViewModel.ProgressValue = size / ViewModel.SelectFileItems.Count * 100);

            // 将主程序添加到数据记录
            if (fileItem.IsSelected)
            {
                assembly.Insert(new MainAssembly
                {
                    Name = fileItem.Name,
                    Id = fileItem.Path
                });
            }
        }

        Close(true);
    }
}